package com.cyf.plc.ui

import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.cyf.library.util.logi
import com.cyf.plc.R
import com.cyf.plc.adapter.FloorAdapter
import com.cyf.plc.base.BaseActivity
import com.cyf.plc.databinding.ActivityPlcHomeBinding
import com.cyf.plc.model.FloorWithRooms
import com.cyf.plc.ui.fragment.PlcRoomFragment
import com.cyf.plc.util.viewModelOf
import com.cyf.plc.viewmodel.PlcViewModel
import kotlinx.android.synthetic.main.activity_plc_home.*
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.greenrobot.eventbus.EventBus

@ExperimentalCoroutinesApi
class PlcHomeActivity : BaseActivity<PlcViewModel, ActivityPlcHomeBinding>(), FloorAdapter.OnItemClickListener {
    override fun createViewModel(): PlcViewModel = viewModelOf(mViewModelProvider)

    private val mAdapter: FloorAdapter by lazy { FloorAdapter(onItemClickListener = this) }

    override fun finish() {
        super.finish()
        overridePendingTransition(0, 0)
    }

    override fun initView() {

        val divider = DividerItemDecoration(this@PlcHomeActivity, DividerItemDecoration.VERTICAL)
        val drawable: Drawable = ContextCompat.getDrawable(this, R.drawable.drawable_custom_divider)!!
        drawable.setBounds(0, 0, 4, 0)
        divider.setDrawable(drawable)

        // Initialize RecyclerView
        mViewBinding.rvFloor.apply {
            layoutManager = LinearLayoutManager(this.context)
            adapter = mAdapter
            addItemDecoration(divider)
        }

        iv_back.setOnClickListener {
            finish()
        }

        mViewModel.getFloorWithRooms().observe(this, Observer {
            //获得楼层数据，加载到Recyclerview

            mAdapter.submitList(it.toMutableList())

            //初始化第一个楼层的房间
            if (it.isNotEmpty())
                onItemClicked(it.get(0))

        })
    }

    override fun onItemClicked(plcFloor: FloorWithRooms) {
        "Click:${plcFloor.plcFloor.floorName}".logi()
        val fragment = getFragment(PlcRoomFragment::class.java)
        if (fragment != null) {
            fragment.updateRooms(plcFloor.plcRooms)
        } else {
            onBackPressed()
            EventBus.getDefault().postSticky(plcFloor.plcRooms)
        }
    }

    override fun onItemLongClick(plcFloor: FloorWithRooms) {

    }

    override fun getViewBinding(): ActivityPlcHomeBinding = ActivityPlcHomeBinding.inflate(layoutInflater)
}
